<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="设备ID" prop="deviceId">
          <el-input
            v-model="queryParams.deviceId"
            placeholder="请输入设备ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input
            v-model="queryParams.model"
            placeholder="请输入设备型号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="安装位置" prop="location">
          <el-input
            v-model="queryParams.location"
            placeholder="请输入安装位置"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="能耗类型" prop="energyType">
          <el-select
            v-model="queryParams.energyType"
            placeholder="请选择能耗类型"
            clearable
            style="width: 192px"
          >
            <el-option
              v-for="item in energyTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 192px"
          >
            <el-option
              v-for="item in deviceStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" plain @click="openForm('create')">
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button type="warning" plain @click="handleExport">
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="list" border>
        <el-table-column label="设备ID" prop="deviceId" min-width="100" />
        <el-table-column label="设备名称" prop="deviceName" min-width="120" />
        <el-table-column label="设备型号" prop="model" min-width="100" />
        <el-table-column
          label="安装位置"
          prop="location"
          min-width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="能耗类型" prop="energyType" min-width="100">
          <template #default="{ row }">
            {{ getEnergyTypeLabel(row.energyType) }}
          </template>
        </el-table-column>
        <el-table-column label="累计能耗(kWh)" prop="energyConsumption" min-width="120" />
        <el-table-column label="状态" prop="status" min-width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          :formatter="dateFormatter"
          min-width="150"
        />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openForm('update', row.id)"> 编辑 </el-button>
            <el-button link type="danger" @click="handleDelete(row.id)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <DeviceForm ref="formRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import * as DeviceApi from '@/api/energy/device'
import { deviceStatusOptions, energyTypeOptions, DeviceVO, exportDevice } from '@/api/energy/device'
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import DeviceForm from './components/DeviceForm.vue'

// 列表数据
const list = ref<any[]>([])
const loading = ref(false)
const total = ref(0)

// 查询条件
const queryFormRef = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: '',
  deviceName: '',
  model: '',
  location: '',
  energyType: '',
  status: '',
  createTime: []
})

// 表单
const formRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await DeviceApi.getDevicePage(queryParams)
    if (res && res.list) {
      list.value = res.list as any
      total.value = res.total
    }
  } finally {
    loading.value = false
  }
}

// 工具方法
const getEnergyTypeLabel = (value: string) => {
  return energyTypeOptions.find((item) => item.value === value)?.label || value
}

const getStatusType = (value: string) => {
  return deviceStatusOptions.find((item) => item.value === value)?.type || ''
}

const getStatusLabel = (value: string) => {
  return deviceStatusOptions.find((item) => item.value === value)?.label || value
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 打开表单
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

// 删除
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认要删除该能耗设备吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await DeviceApi.deleteDevice(id)
    ElMessage.success('删除成功')
    handleQuery()
  })
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 显示导出进度
    ElMessage.success('正在导出能耗设备数据，请稍候...')
    // 执行导出
    const res = await exportDevice(queryParams)
    console.log('导出响应:', res) // 添加调试信息
  } catch (error: any) {
    console.error('导出错误:', error) // 添加错误详情日志
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 页面加载时查询数据
onMounted(() => {
  getList()
})
</script>
